package com.match.util;

import com.match.entry.Mail;
import com.match.entry.MailAttach;

import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.*;
import javax.mail.internet.*;
import java.io.UnsupportedEncodingException;

public class SendMailUtil {
    private final static String RESOURCE_URL = "src/main/resources/";

    /**
     * @param mail
     * @throws Exception
     */
    public static void sendMail(Mail mail) {
        //使用JavaMail发送邮件的5个步骤
        //1、创建session
        Session session = MailSessionUtil.createSessionUtil(mail);
        //开启Session的debug模式，这样就可以查看到程序发送Email的运行状态
//        session.setDebug(false);
        session.setDebug(true);
        //2、通过session得到transport对象
        Transport ts = null;
        try {
            ts = session.getTransport();
            //3、连上邮件服务器
            ts.connect();
            //4、创建邮件
            Message message = createMixedMail(session, mail);
            //5、发送邮件
            ts.sendMessage(message, message.getAllRecipients());
        } catch (Exception e) {
            try {
                System.out.println(MimeUtility.encodeText(e.getMessage()));
            } catch (UnsupportedEncodingException e1) {
                e1.printStackTrace();
            }
            e.printStackTrace();
        } finally {
            try {
                if (ts != null) {
                    ts.close();
                }
            } catch (MessagingException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * @param session
     * @return
     * @throws Exception
     * @Method: createMixedMail
     * @Description: 生成一封带附件和带图片的邮件
     */
    private static MimeMessage createMixedMail(Session session, Mail mail) throws Exception {
        //创建邮件
        MimeMessage message = new MimeMessage(session);

        //设置邮件的基本信息
        message.setFrom(new InternetAddress(mail.getFromEmail()));
        message.setRecipient(Message.RecipientType.TO, new InternetAddress(mail.getRecipient()));
        message.setSubject(mail.getSubject());

        //代表正文的bodypart
        MimeBodyPart content = new MimeBodyPart();
        //设置正文
        MimeMultipart mp1 = setContent(mail);


        //描述关系:正文和附件
        MimeMultipart mp2 = setAttach(mail);
        //添加正文
        if(mp1 != null) {
            content.setContent(mp1);
            mp2.addBodyPart(content);
            mp2.setSubType("mixed");
        }

        message.setContent(mp2);
        message.saveChanges();
//        message.writeTo(new FileOutputStream("E:\\MixedMail.eml"));
        //返回创建好的的邮件
        return message;
    }

    /**
     * 设置邮件正文
     * @param mail
     * @return
     * @throws MessagingException
     */
    private static MimeMultipart setContent(Mail mail) throws MessagingException {

        //正文内容
        if (mail.getMailContentList() != null && !mail.getMailContentList().isEmpty()) {
            //描述关系:正文和图片
            MimeMultipart mp1 = new MimeMultipart();
            mp1.setSubType("related");
            for (MailAttach attach : mail.getMailContentList()) {
                if (attach.getContent() != null) {
                    MimeBodyPart bodyPart = new MimeBodyPart();
                    //设置内容时需要设置图片链接
                    bodyPart.setContent(attach.getContent() + "<img src='cid:" + attach.getFileName() + "'>", "text/html;charset=UTF-8");
                    mp1.addBodyPart(bodyPart);
                }
                if (attach.getFileName() != null) {
                    //设置图片附件
                    MimeBodyPart bodyPart = new MimeBodyPart();
                    DataHandler dh = new DataHandler(new FileDataSource(RESOURCE_URL + attach.getFileName()));
                    bodyPart.setDataHandler(dh);
                    if (attach.isPic()) {
                        bodyPart.setContentID(attach.getFileName());
                    }
                    mp1.addBodyPart(bodyPart);
                }
            }
            return mp1;
        }
        return null;
    }

    /**
     * 设置附件
     * @param mail
     * @return
     * @throws MessagingException
     * @throws UnsupportedEncodingException
     */
    private static MimeMultipart setAttach(Mail mail) throws MessagingException, UnsupportedEncodingException {
        MimeMultipart mp2 = new MimeMultipart();
        //添加附件
        if (mail.getMailAttachList() != null && !mail.getMailAttachList().isEmpty()) {
            for (MailAttach mailAttach : mail.getMailAttachList()) {
                MimeBodyPart attach = new MimeBodyPart();
                if (mailAttach.getFileName() != null) {
                    //附件
                    DataHandler dh = new DataHandler(new FileDataSource(RESOURCE_URL + mailAttach.getFileName()));
                    attach.setDataHandler(dh);
                    attach.setFileName(MimeUtility.encodeText(dh.getName()));
                }
                mp2.addBodyPart(attach);
            }
        }
        return mp2;
    }
}
